package com.goodfather.textbook.youdao.pad.weight;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by XLee on 2017/11/15.
 */

@SuppressLint("AppCompatCustomView")
public class AudioImageView extends ImageView {

    private Bitmap mBitmap;

    public AudioImageView(Context context) {
        this(context, null);
    }

    public AudioImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        this.mBitmap = bm;
        super.setImageBitmap(bm);
    }

    public Drawable getClipBitmap(RectF rectF) {
        Bitmap bitmap = ImageCrop(rectF.left, rectF.top, rectF.width(), rectF.height());
        return new BitmapDrawable(getResources(), bitmap);
    }

    /**
     * 裁切图片
     *
     * @param startX
     * @param startY
     * @param width
     * @param height
     */
    public Bitmap ImageCrop(float startX, float startY, float width, float height) {
        if (mBitmap == null) return null;
        // java.lang.IllegalArgumentException: width must be > 0
        if (width <= 0 || height <= 0)return null;
        int w = mBitmap.getWidth(); // 得到图片的宽，高
        int h = mBitmap.getHeight();
        if (startX <0) startX = 0;
        if (startY <0) startY = 0;

        if (width > w){
            width = w;
        }

        if (height > h){
            height = h;
        }
        if (startX >= w || startY >= h){
            return null;
        }
        if (startX + width > w){
            width = w - startX;
        }

        //下面这句是关键
        return Bitmap.createBitmap(mBitmap, (int) startX, (int) startY, (int) width, (int) height, null, false);
    }

    public Bitmap getmBitmap() {
        return mBitmap;
    }
}
